import * as jwt from 'jsonwebtoken';
// onst Controller = require("egg").Controller
// const user = require("../model/user");
import { Controller, Provide, App, Inject, Post } from '@midwayjs/decorator';
import { Application, Context } from 'egg';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { Users } from '../entity/Users';
import { LocalAccounts } from '../entity/LocalAccounts';
import { Companys } from '../entity/Companys';

const Appid = 1400492989;
const TemplateID = 885672;

@Provide()
@Controller('/api')
export default class UserController {

  @App()
  app: Application;

  @Inject()
  ctx: Context;

  @InjectEntityModel(Users)
  userModel:Repository<Users>

  @InjectEntityModel(LocalAccounts)
  acountModel:Repository<LocalAccounts>

  @InjectEntityModel(Companys)
  companyModel:Repository<Companys>

  async sms_verify() {
    const { app } = this;
    console.log(app.sms);

    this.ctx.hello
  }

  async sms() {
    const { ctx, app } = this;
    const data = ctx.request.body;
    const code = (100000 + Math.floor(Math.random() * 899999)).toString();

    await app.tencentcloudSms.SendSms({
      PhoneNumberSet: ['+86' + data.mobile],
      TemplateParamSet: [code],
      TemplateID,
      SmsSdkAppid: Appid,
      Sign: '掌银互娱',
    }).then(res => {
      console.log(res);
      app.sms[data.mobile] = code;
      ctx.success('成功发送');
    })
      .catch(err => {
        console.log(err.message);
        err.message;
        err.code;
        err.requestId;
        err.getMessage();
        err.getRequestId();
      });
  }


  @Post('/socketUrl', { middleware: ['tokenVerifyMiddleware'] })
  async socketUrl() {
    //const { app } = this;
    //const { ctx } = this;
    //const data = ctx.request.body;

    const user_id = this.ctx.user.id;

    
    const result = await this.userModel.query(`SELECT
      u.id as user_id,
      u.name as user_name,
      p.id as company_id,
      p.name as company_name,
      c.serise_id as serise_id,
      c.name as collecor_name,
      c.push_host as push_host,
      c.push_port as push_port,
      c.uri as push_url
      FROM
      (SELECT id,name,company_id FROM users WHERE id=${user_id}) as u
      LEFT JOIN (SELECT id,name FROM companys) as p ON p.id=u.company_id
      LEFT JOIN (SELECT company_id,serise_id,name,push_host,push_port,uri FROM collectors) as c  ON c.company_id=u.company_id`
    )

    const collector: any = result[0]

    this.ctx.success(null,JSON.stringify(collector));
  }

  @Post('/login', { middleware: ['tokenVerifyMiddleware'] })
  async login() {
    const { app } = this;
    const { ctx } = this;
    const data = ctx.request.body;
    //ctx.logger.debug(data);

    //ctx.logger.debug('WW');


    try {
      ctx.validate({ username: 'string', password: { type: 'string', allowEmpty: false } }, data);
    } catch (err) {
      ctx.error(app.ErrorCode.INPUT_INVALIDE);
      return;
    }

    let account = await this.acountModel.findOneOrFail(data.username)

    // const account = await ctx.model.LocalAccount.findOne({
    //   where: {
    //     username: {
    //       [Op.eq]: data.username,
    //     },
    //   },
    // });

    let md5 = app.utils.md5(data.password)
    if (account !== null && md5 === account.password) {
      //ctx.logger.debug(account);

      //const user = await ctx.model.User.findByPk(account.user_id)

      let user = await this.userModel.findOne(account.user_id)

      let company = await this.companyModel.findOne(user.company_id)

      if (user != null /* && pakage != null*/) {

        // let soil = 10000000 * Math.floor(Math.random() * 89999999)
        const expireTime = Math.floor(Date.now() / 1000) + app.config.token.duration;
        const data = { user_id: account.user_id, expireTime };
        const token = jwt.sign(data, app.config.token.secretKey);
        this.ctx.success('登录成功', {
          auth: token,
          mch_id: company.name,
          role: user.role,
          company_id: user.company_id,
          expireTime,
        });

        console.log(data);
        // ctx.session.uuid = account.uuid
        // ctx.session.user = user
        // ctx.session.pakage = pakage
        //ctx.logger.debug(data);
        // ctx.logger.debug(pakage)
        return;
      }
    }

    ctx.error(app.ErrorCode.ACCOUNT_NOT_EXIST);
  }

  async logout() {
    const { ctx } = this;
    ctx.session.user = undefined;
    ctx.success('登出成功');
  }

  async userinfo() {
    const { ctx } = this;
    // ctx.body = ctx.user
    const user_id = ctx.user.id;

    const user = await ctx.model.User.findByPk(user_id);

    ctx.body = user?.toJSON();

    // ctx.body = ctx.session.user.name
  }

  async register() {
    const { ctx, app } = this;
    //ctx.logger.debug(ctx.request.body);
    let data = ctx.request.body;

    console.log(data);
    try {
      ctx.validate({ username: 'string', password: { type: 'string', allowEmpty: false }, code: 'string' });
    } catch (err) {
      ctx.error(app.ErrorCode.INPUT_INVALIDE);
      return;
    }

    //-- 验证码校验
    let code = app.sms[data.username]
    //清除验证码
    app.sms[data.username] = undefined

    if (!code) {
      ctx.error(app.ErrorCode.SMS_CODE_INVALIDE)
      return
    }

    // --- 查询注册
    try {
      const localAccount = await ctx.model.LocalAccount.findAll({
        where: {
          username: data.username,
        },
      });

      if (localAccount.length > 0) {
        ctx.body = ctx.errorText(app.ErrorCode.ACCOUNT_ALRADY_EXIST); // "{code:'FAILED',msg:'account is exist.'}"
        return;
      }

      //--检查上级代理
      if (!data.mch_id) //如果创建零账号需要白名单
      {
        let result = await ctx.model.WhiteList.findOne({
          where: {
            username: data.username
          }
        })

        if (!result) {
          ctx.error(ctx.app.ErrorCode.REGISTER_NEED_IN_WHITE_LIST)
          return
        }
      } else {
        let result = await ctx.model.User.findByPk(data.mch_id)

        if (!result || result.parent_id != 10000) {
          ctx.error(ctx.app.ErrorCode.REGISTER_AGENT_IS_INVALID)
          return
        }
      }

      let newUser:any = {
        parent_id: data.mch_id,
        phone: data.username
      }

      //const user = await ctx.model.User.create(<any>newUser)

      let user = await this.userModel.create(<{}>newUser)

      data.user_id = user.id
      data.password = app.utils.md5(data.password)
      user.phone = data.username
      user.name = user.id.toString()
      
      user = await this.userModel.save(user)
      //const account = await ctx.model.LocalAccount.create(data)

      const account = await this.acountModel.create(<{}>data)
    
      console.log(JSON.stringify(account));
      console.log(JSON.stringify(user));

      ctx.success('注册成功2');
      return;

    } catch (error) {
      console.log(error);
      ctx.body = ctx.errorText(app.ErrorCode.ACCOUNT_CREATE_ERROR);
    }
  }
}

module.exports = UserController;
